<?php
/**
 * @author Truong Kim Phung
 * @copyright 2014
 * @description: save action sample. modified code Pham Van Diep
 */
// not login
// not perm add
if(!isset($AppUI->id)) {
    redirect(isset($_SESSION[SESSION_BACKURL]) ? $_SESSION[SESSION_BACKURL] : HOST_BACKEND);
}
// data input
$strUsername        = $this->input->post('pusername',null); 
$strPassword    	= $this->input->post('ppassword',null);			
$strConfirmPassword = $this->input->post('ppassword_confirm',null);
$strFullname        = $this->input->post('pfullname', null);
$intType            = (int)$this->input->post('ptype', 0);
$intRoomId          = (int)$this->input->post('proomid', 0);
$arrErr             = array();
// strip tag data input
$strUsername        = CI_Function::stripTag($strUsername);
$lenUsername        = strlen($strUsername);
$lenPassword        = strlen($strPassword);
$strFullname        = CI_Function::stripTag($strFullname);
$lenFullname        = strlen($strFullname);
// validate manual	
//+ username	
if(!isset($strUsername) || empty($strUsername))
    array_push($arrErr, $arrLocale['username_required']);
elseif(isset($strUsername) && ($lenUsername < VL_USERNAME_MINLENGTH || $lenUsername > VL_USERNAME_MAXLENGTH) ) 
    array_push($arrErr, $arrLocale['username_range']);
//+ password
if(!isset($strPassword) || empty($strPassword))
    array_push($arrErr, $arrLocale['password_required']);
elseif(isset($strPassword) && $lenPassword < VL_PASSWORD_MINLENGTH) 
    array_push($arrErr, $arrLocale['password_minlength']);
elseif(isset($strPassword) && $strPassword != $strConfirmPassword)
    array_push($arrErr, $arrLocale['password_notmatch']);
//+ confirm password
if(!isset($strConfirmPassword) || empty($strConfirmPassword))
    array_push($arrErr, $arrLocale['password_confirm_required']);
    
if(isset($arrErr) && count($arrErr)==0) {//allow save
    // unset session if exists
    if(isset($_SESSION['ADMIN_ERROR'])) unset($_SESSION['ADMIN_ERROR']);
    if(isset($_SESSION['ADMIN_POST'])) unset($_SESSION['ADMIN_POST']);
    $this->load->model('admin_model', 'admin');	    
    $intError = $this->admin->add($AppUI->id, $strUsername, md5($strPassword), $strFullname, $intType, $intRoomId);
    if($intError==0) CI_Function::setMsg($arrMessage['save_add']);
    elseif($intError==1) array_push($arrErr, $arrLocale['username_validate']);
    elseif($intError==2) array_push($arrErr, $arrError['noperm_save']);        
}
// occur error

if (isset($arrErr) && count($arrErr) > 0) {
    $_SESSION['ADMIN_ERROR']    = $arrErr;    
    $_SESSION['ADMIN_POST']     = $this->input->post();
    
    redirect(HOST_BACKEND . 'admin/add');
}
redirect(isset($_SESSION[SESSION_BACKURL]) ? $_SESSION[SESSION_BACKURL] : HOST_BACKEND);
